package com.example.demo;
 
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.openai.OpenAiEmbeddingOptions;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * User: ldj
 * Date: 2024/7/7
 * Time: 15:03
 * Description: AI 聊天controller
 */
@RestController
@RequestMapping("/chat")
public class ChatController {

    private final ChatClient chatClient;

    @Autowired
    VectorStore vectorStore;

    public ChatController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }
 
    @GetMapping("/normal")
    public String generation(@RequestParam(value = "question", defaultValue = "使用中文简短介绍自己") String question) {
        UserMessage userMessage = new UserMessage(question);
        SystemMessage systemMessage = new SystemMessage("用小弟的口吻回答，称呼用户为老大");

        return this.chatClient.getClass()+this.chatClient
                .prompt(new Prompt(userMessage, systemMessage))
                .call()
                .content();
    }

    @GetMapping("/rag")
    public String rag(@RequestParam(value = "question", defaultValue = "") String question) {

        SearchRequest searchRequest = SearchRequest.builder().query(question).topK(4).build();
        List<Document> results = this.vectorStore.similaritySearch(searchRequest);
        StringBuilder searchRes= new StringBuilder();
        if (results != null) {
            for (Document result : results) {
                searchRes.append(result.getText()).append("\n");
            }
        }

        UserMessage userMessage = new UserMessage(question);
        SystemMessage systemMessage=new SystemMessage("用小弟的口吻，给用户大哥一点旅游建议，提供以下信息"+searchRes.toString());
        return this.chatClient
                .prompt(new Prompt(userMessage, systemMessage))
                .call()
                .content();
    }



}